//
//  NSString+URLParser.m
//  OMTCoreKit
//
//  Created by 昭荣伊 on 2018/7/27.
//

#import "NSString+URLParser.h"
#import "NSString+Coder.h"

@implementation NSString (URLParser)

- (NSString *)omt_appendURLParams:(NSDictionary *)params {
    if (params.allKeys.count < 1) return self;
    
    NSMutableArray *pairs = [NSMutableArray array];
    for ( NSString *key in params.allKeys ) {
        NSString *value = [params[key] omt_URLEncode];
        [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, value]];
    }
    NSURL *URL = [NSURL URLWithString:self];
    NSString *prefix = @"";
    if (URL.absoluteString.length > 0) {
        prefix = URL.query ? @"&" : @"?";
    }
    NSString *paramsString = [pairs componentsJoinedByString:@"&"];
    NSString *target = [self stringByAppendingString:[NSString stringWithFormat:@"%@%@", prefix, paramsString]];
    return target;
}

- (NSString *)omt_appendURLArray:(NSArray *)array {
    // 组装参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    for ( NSUInteger i = 0; i < [array count]; i += 2 ) {
        if (i >= array.count || i + 1 >= array.count) {
            break;
        }
        
        NSObject * obj1 = [array objectAtIndex:i];
        NSObject * obj2 = [array objectAtIndex:i + 1];
        
        NSString * key = nil;
        NSString * value = nil;
        
        if ( [obj1 isKindOfClass:[NSNumber class]] ) {
            key = [(NSNumber *)obj1 stringValue];
        } else if ( [obj1 isKindOfClass:[NSString class]] ) {
            key = (NSString *)obj1;
        } else {
            continue;
        }
        
        if ( [obj2 isKindOfClass:[NSNumber class]] ) {
            value = [(NSNumber *)obj2 stringValue];
        } else if ( [obj1 isKindOfClass:[NSString class]] ) {
            value = (NSString *)obj2;
        } else {
            continue;
        }
        
        value = [value omt_URLEncode];
        if (key) {
            params[key] = value;
        }
    }
    return [self omt_appendURLParams:params];
}

- (NSDictionary *)omt_URLParams {
    NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
    // Extract Params From Query.
    NSArray<NSURLQueryItem *> *queryItems = [[NSURLComponents alloc] initWithURL:[[NSURL alloc] initWithString:self] resolvingAgainstBaseURL:false].queryItems;
    
    for (NSURLQueryItem *item in queryItems) {
        parameters[item.name] = item.value;
    }
    return [parameters copy];
}

- (NSString *)omt_URLParamValueForKey:(NSString *)key {
    return [self omt_URLParams][key];
}

@end
